<?php

/**
 * This is the model class for table "{{tag_goods}}".
 *
 * The followings are the available columns in table '{{tag_goods}}':
 * @property string $TagID
 * @property string $Title
 * @property string $GoodsID
 * @property string $GoodsBmID
 * @property string $AddTime
 */
class TagGoodsModel extends BaseModel
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{tag_goods}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('TagID', 'required'),

			array('GoodsID', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('TagID,GoodsID, AddTime', 'safe', 'on'=>'admin'),
			array('TagID, TagGoodsID, GoodsID, AddTime', 'safe', 'on'=>'search'),
		);
	}
	public function beforeSave(){
		if($this->isNewRecord){
			$this->AddTime = time();
		}
		return true;
	}
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			//self::HAS_MANY  我的这个表的主键去关联TagGoodsModel这个表的GoodsID这个字段  
			//self::BELONGS_TO  我的这个表的GoodsName 去关联 TagGoodsModel这个表的主键
			//self::HAS_ONE 我的这个表的主键去关联TagGoodsModel的GoodssID
			'GoodsModel' => array(self::BELONGS_TO, 'GoodsModel', 'GoodsID'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'TagGoodsID' => '主键ID',
			'TagID' => '标签ID',


			'GoodsID' => '商品ID',
			'AddTime' => '添加时间',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('TagID',$this->TagID,true);
		$criteria->compare('GoodsID',$this->GoodsID,true);
		$criteria->compare('AddTime',$this->AddTime,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	public function createSearchCriteria()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('t.TagID',$this->TagID);
		$criteria->compare('t.GoodsID',$this->GoodsID,true);
		$criteria->compare('AddTime',$this->AddTime,true);

		return $criteria;
	}
	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return TagGoodsModel the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	//根据商品ID取所有的列表
	public static function getList($GoodsID, $bloIsCache = true){
		$strCache = 'TagGoodsModel_getList' . '_' . $GoodsID;
		$arrCache = yii::app()->cache->get($strCache);
        //如果不是取缓存数据  或者 缓存已经过期
        if($bloIsCache && $arrCache !== false){
            return $arrCache;
        }

        $arrResult = array();
        $objModels = self::model()->findAll(BaseModel::getC(array('GoodsID' => $GoodsID)));
        foreach ($objModels as $key => $objModel) {
        	$arrResult[$objModel->TagGoodsID] = $objModel->attributes;
        }
        yii::app()->cache->set($strCache, $arrResult, 600);
        return $arrResult;
	}

	//根据商品ID取这列表根据字段来取
	public static function getListField($GoodsID, $field){
		$datas = self::getList($GoodsID);
        $arrResult = array();
        foreach ($datas as $key => $data) {
        	$arrResult[$key] = $data[$field];
        }
        return $arrResult;
	}


	//根据标签ID取这标签所有的商品
	public static function getListGoods($TagID, $bloIsCache = true){
		$strCache = 'TagGoodsModel_getListGoods' . '_' . $TagID;
		$arrCache = yii::app()->cache->get($strCache);
        //如果不是取缓存数据  或者 缓存已经过期
        if($bloIsCache && $arrCache !== false){
            return $arrCache;
        }

        $arrResult = array();
        $objModels = self::model()->findAll(BaseModel::getC(array('TagID' => $TagID)));
        foreach ($objModels as $key => $objModel) {
        	$arrResult[$objModel->TagGoodsID] = $objModel->attributes;
        }
        yii::app()->cache->set($strCache, $arrResult, 600);
        return $arrResult;
	}

	//根据标签ID取所有的数据 取出某字段
	public static function getListGoodsField($TagID, $field){
		$datas = self::getListGoods($TagID);
        $arrResult = array();
        foreach ($datas as $key => $data) {
        	$arrResult[$key] = $data[$field];
        }
        return $arrResult;
	}






	public function afterSave(){
		$this->getList($this->GoodsID, false);
	}
	//当这个标签删除了之后，我需要删除与其关联的goods_id记录
	public function afterDelete(){		
		$this->getList($this->GoodsID, false);
	}

	/**
	 * 通过标签名与商品ID，看是否需要添加此标签，并把这商品ID加入到这个标签
	 * @param  [type] $strTagName [description]
	 * @param  [type] $GoodsID    [description]
	 * @return [type]             [description]
	 */
	public static function saveDataTag($strTagName, $GoodsID){
		$objModel = TagModel::model()->find(BaseModel::getC(array('Title' => $strTagName)));
		if($objModel){
			//能找到此标签的情况下，如果不能找到此标签的商品，则添加
			$obj = self::model()->find(BaseModel::getC(array('GoodsID' => $GoodsID, 'TagID' => $objModel->TagID)));
			if(!$obj){
				$arrData = array(
					'TagID' => $objModel->TagID,
					'GoodsID' => $GoodsID,				
				);				
				$obj = new TagGoodsModel();
				$obj->attributes = $arrData;
				$obj->save($arrData);				
			}
		}else{
			//如果找不到此标签，，则先保存此标签，然后再添加到商品标签里。。。
			$objModel = new TagModel();
			$objModel->Title = $strTagName;
			$objModel->save();
			$arrData = array(
				'TagID' => $objModel->TagID,
				'GoodsID' => $GoodsID,				
			);
			$obj = new TagGoodsModel();
			$obj->attributes = $arrData;
			$obj->save($arrData);
		}
	}


	/**
	 * 保存数据，能过标签ID，与商品ID
	 * @param  [type] $TagID   [description]
	 * @param  [type] $GoodsID [description]
	 * @return [type]          [description]
	 */
	public static function saveData($TagID, $GoodsID){
		$data = array(
			'TagID' => $TagID,
			'GoodsID' => $GoodsID,
		);
		$objModel = new TagGoodsModel();
		$objModel->attributes = $data;
		$objModel->save(false);
	}

}
